﻿using Force.DeepCloner;
using Shinva.Variables.Interface;
using Shinva.Variables.Models;
using Shinva.Variables.Type.bit;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;

namespace Shinva.Variables.Type.combination
{
    public class PlcArray : PlcComplexBase//PlcMemberBase
    {
        /// <summary>
        /// 数组元素
        /// </summary>
        //private  List<IPlcMember> _elements;
       // private readonly List<IPlcMember> _elements = new List<IPlcMember>();

        /// <summary>
        /// 数组占用字节数
        /// </summary>
       // private readonly int _elementSizeInBytes;

        /// <summary>
        /// 数组元素类型
        /// </summary>
       // public DataType ElementType { get; }

        /// <summary>
        /// 数组的长度
        /// </summary>
        /// 
        public DataType MemberDataType { get; private set; }
        public int Length => GetMembers().Count;

        //public IReadOnlyList<IPlcMember> Elements => _elements;

        public PlcArray(string _name, IPlcMember element, int length)
        {
            //属性赋值
            Name=_name;
            DataType = DataType.Array;
            SizeInBits = CalculateTotalSize(element, length);
            // 验证原型有效性
            if (element == null) throw new ArgumentNullException(nameof(element));
            if (length <= 0) throw new ArgumentOutOfRangeException(nameof(length));

            // 初始化元素
            MemberDataType = element.DataType;
            int _elementSizeInBytes = element.SizeInBytes();
           //_members = new List<IPlcMember>();

            // 创建元素实例并设置地址
            for (int i = 0; i < length; i++)
            {
                var _element = element.DeepClone();
                _element.Name = $"{_name}[{i}]";
                _element.Address = new PlcAddress(
                    byteOffset: i * _elementSizeInBytes,
                    bitOffset: 0);
                _element.Parent = this;
                this.AddMember(_element);
            }
        }

 

        private static int CalculateTotalSize(IPlcMember prototype, int length)
        {
            return prototype.SizeInBits * length;
        }




    }
}
